from jose import jwt
from datetime import datetime, timedelta
from api.application import settings
from typing import Optional
import uuid


class use_JWT(object):
    JWTError = jwt.JWTError
    ExpiredSignatureError = jwt.ExpiredSignatureError

    def __init__(self):
        self.secret_ket = settings.JWT.get('secret_key')
        self.algorithm = settings.JWT.get('algorithm')
        self.expire_time = settings.JWT.get('expire_time')

    def create_JWT(self, data: dict, ex: Optional[int] = None):
        print("secret_key:::", settings.JWT.get('secret_key'))
        print("algorithm:::", settings.JWT.get('algorithm'))
        print("expire_time:::", settings.JWT.get('expire_time'))

        now_time = datetime.utcnow()
        if ex is not None:
            guoqi_time = datetime.utcnow() + timedelta(seconds=ex)
        else:
            guoqi_time = datetime.utcnow() + timedelta(seconds=self.expire_time)

        payload = {
            "exp": guoqi_time,
            "iat": now_time,
            "nbf": now_time,
            "jti": str(uuid.uuid4())
        }
        payload.update(data)

        return jwt.encode(payload, self.secret_ket, algorithm=self.algorithm)

    def verify_jwt(self, token: str):
        paylod = jwt.decode(token, self.secret_ket, algorithms=[self.algorithm])
        return paylod


JwtToken = use_JWT()
